<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="日期" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="凭证日期" prop="voucherDateRange">
        <el-date-picker
          v-model="voucherDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="凭证字号" prop="voucherNo">
        <el-input
          v-model="queryParams.voucherNoStart"
          style="width: 100px"
          placeholder="起始号"
        />
        <span class="mx-2">至</span>
        <el-input
          v-model="queryParams.voucherNoEnd"
          style="width: 100px"
          placeholder="结束号"
        />
      </el-form-item>
      <el-form-item label="转出账户" prop="accountOut" style="width: 160px">
        <el-select v-model="queryParams.accountOut" placeholder="请选择">
          <el-option
            v-for="dict in cash_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="转入账户" prop="accountJoin" style="width: 160px">
        <el-select v-model="queryParams.accountJoin" placeholder="请选择">
          <el-option
            v-for="dict in cash_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            style="width: 200px"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:transfer:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:transfer:export']"
          >导出</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:transfer:import']"
          >导入</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleDelete"
          v-hasPermi="['system:transfer:remove']"
          >批量删除</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="transferList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编码" align="center" prop="id" width="50" />
      <el-table-column
        label="日期"
        align="center"
        prop="createTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="再要" align="center" prop="insideAbstract" />
      <el-table-column label="转出账户" align="center" prop="accountOut">
        <template #default="scope">
          <dict-tag :options="cash_name" :value="scope.row.accountOut" />
        </template>
      </el-table-column>
      <el-table-column label="转入账户" align="center" prop="accountJoin">
        <template #default="scope">
          <dict-tag :options="cash_name" :value="scope.row.accountJoin" />
        </template>
      </el-table-column>
      <el-table-column label="转账金额" align="center" prop="accountLimit" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="制单人" align="center" prop="userId">
        <template #default="scope">
          <dict-tag :options="user_name" :value="scope.row.userId" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:transfer:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:transfer:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="primary"
            icon="Upload"
            @click="handleGenerateVoucher(scope.row)"
            v-hasPermi="['system:transfer:remove']"
            >生成凭证</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内部转账记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="transferRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="再要" prop="insideAbstract">
          <el-input v-model="form.insideAbstract" placeholder="请输入再要" />
        </el-form-item>
        <el-form-item label="转出账户" prop="accountOut">
          <el-select v-model="form.accountOut" placeholder="请选择转出账户">
            <el-option
              v-for="dict in cash_name"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转入账户" prop="accountJoin">
          <el-select v-model="form.accountJoin" placeholder="请选择转入账户">
            <el-option
              v-for="dict in cash_name"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转账金额" prop="accountLimit">
          <el-input
            v-model="form.accountLimit"
            placeholder="请输入转账金额"
            type="number"
            min="0"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="制单人" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择制单人">
            <el-option
              v-for="dict in user_name"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加生成凭证对话框 -->
    <el-dialog
      :title="'生成凭证'"
      v-model="voucherOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="voucherFormRef"
        :model="voucherForm"
        :rules="voucherRules"
        label-width="100px"
      >
        <el-form-item label="凭证日期" prop="voucherDate" required>
          <el-date-picker
            v-model="voucherForm.voucherDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="凭证字号" prop="voucherWord" required>
          <el-select
            v-model="voucherForm.voucherWord"
            placeholder="请选择凭证字"
            style="width: 120px"
          >
            <el-option label="记" value="J" />
            <el-option label="收" value="S" />
            <el-option label="付" value="F" />
          </el-select>
          <span class="mx-2">-</span>
          <el-input
            v-model="voucherForm.voucherNo"
            placeholder="凭证号"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="会计科目" prop="accountCode" required>
          <el-select
            v-model="voucherForm.accountCode"
            placeholder="请选择会计科目"
            style="width: 100%"
          >
            <el-option label="银行存款" value="1002" />
            <el-option label="库存现金" value="1001" />
            <el-option label="其他货币资金" value="1012" />
          </el-select>
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="voucherForm.summary" placeholder="请输入摘要" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="voucherForm.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="附单据数" prop="attachmentCount">
          <el-input-number
            v-model="voucherForm.attachmentCount"
            :min="0"
            :max="999"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitVoucherForm">确 定</el-button>
          <el-button @click="cancelVoucher">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Transfer">
import {
  listTransfer,
  getTransfer,
  delTransfer,
  addTransfer,
  updateTransfer,
  delTransfers,
  generateVoucher,
} from "@/api/system/transfer";
import { getToken } from "@/utils/auth";
import { Upload } from "@element-plus/icons-vue";
import { ElLoading } from "element-plus";

const { proxy } = getCurrentInstance();
const { cash_name, user_name } = proxy.useDict("cash_name", "user_name");

const transferList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const dateRange = ref([]);
const voucherDateRange = ref([]);

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/system/transfer/importData",
});

// 添加校验规则常量
const SINGLE_LIMIT = 1000000; // 单笔限额 100万
const DAILY_LIMIT = 5000000; // 每日限额 500万
/** 自定义校验方法 - 账户不能相同 */
const validateAccounts = (rule, value, callback) => {
  if (form.value.accountOut === form.value.accountJoin) {
    callback(new Error("转出账户和转入账户不能相同"));
  } else {
    callback();
  }
};

/** 自定义校验方法 - 金额校验（不能为负数和0） */
const validateAmount = (rule, value, callback) => {
  if (!value) {
    callback(new Error("金额不能为空"));
  }
  const amount = parseFloat(value);
  if (isNaN(amount)) {
    callback(new Error("请输入有效的数字金额"));
  }
  if (amount <= 0) {
    callback(new Error("金额必须大于0"));
  }
  if (amount > SINGLE_LIMIT) {
    callback(new Error(`单笔转账金额不能超过${SINGLE_LIMIT}元`));
  }
  callback();
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateStart: null,
    dateEnd: null,
    voucherDateStart: null,
    voucherDateEnd: null,
    voucherNoStart: null,
    voucherNoEnd: null,
    accountOut: null,
    accountJoin: null,
    accountLimit: null,
  },
  rules: {
    id: [{ required: true, message: "编码不能为空", trigger: "blur" }],
    createTime: [{ required: true, message: "日期不能为空", trigger: "blur" }],
    insideAbstract: [
      { required: true, message: "摘要不能为空", trigger: "blur" },
    ],
    accountOut: [
      { required: true, message: "转出账户不能为空", trigger: "change" },
      { validator: validateAccounts, trigger: "change" },
    ],
    accountJoin: [
      { required: true, message: "转入账户不能为空", trigger: "change" },
      { validator: validateAccounts, trigger: "change" },
    ],
    accountLimit: [
      { required: true, message: "转出金额不能为空", trigger: "blur" },
      { validator: validateAmount, trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 添加凭证表单相关变量
const voucherOpen = ref(false);
const voucherForm = ref({
  voucherDate: "",
  voucherWord: "J",
  voucherNo: "",
  accountCode: "",
  summary: "",
  remark: "",
  attachmentCount: 1,
  transferId: null,
  transferData: null, // 添加转账数据字段，用于保存完整的内部转账数据
});

// 添加凭证表单校验规则
const voucherRules = {
  voucherDate: [
    { required: true, message: "凭证日期不能为空", trigger: "blur" },
  ],
  voucherWord: [
    { required: true, message: "凭证字不能为空", trigger: "change" },
  ],
  voucherNo: [
    { required: true, message: "凭证号不能为空", trigger: "blur" },
    { pattern: /^\d+$/, message: "凭证号必须为数字", trigger: "blur" },
  ],
  accountCode: [
    { required: true, message: "会计科目不能为空", trigger: "change" },
  ],
  summary: [{ required: true, message: "摘要不能为空", trigger: "blur" }],
};

/** 查询内部转账记录列表 */
function getList() {
  loading.value = true;
  listTransfer(queryParams.value).then((response) => {
    transferList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    insideAbstract: null,
    accountOut: null,
    outLimit: null,
    accountJoin: null,
    joinLimit: null,
    remark: null,
    userId: null,
  };
  proxy.resetForm("transferRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  // 处理日期范围
  if (dateRange.value) {
    queryParams.value.dateStart = dateRange.value[0];
    queryParams.value.dateEnd = dateRange.value[1];
  }
  if (voucherDateRange.value) {
    queryParams.value.voucherDateStart = voucherDateRange.value[0];
    queryParams.value.voucherDateEnd = voucherDateRange.value[1];
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  voucherDateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加内部转账记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getTransfer(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改内部转账记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["transferRef"].validate((valid) => {
    if (valid) {
      // 原有的提交逻辑
      if (form.value.id != null) {
        updateTransfer(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTransfer(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const transferIds = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除内部转账记录编号为"' + transferIds + '"的数据项？')
    .then(function () {
      return delTransfers(transferIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/transfer/export",
    {
      ...queryParams.value,
    },
    `transfer_${new Date().getTime()}.xlsx`
  );
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "内部转账数据导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "system/transfer/importTemplate",
    {},
    `transfer_template_${new Date().getTime()}.xlsx`
  );
}

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].clearFiles();
  proxy.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

// 提交上传文件
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

// 生成凭证按钮操作
function handleGenerateVoucher(row) {
  // 先获取完整的内部转账记录数据
  const transferId = row.id || ids.value;
  getTransfer(transferId).then((response) => {
    const transferData = response.data;

    // 使用获取到的完整数据初始化凭证表单
    voucherForm.value = {
      // 凭证特有字段
      voucherDate: new Date().toISOString().split("T")[0],
      voucherWord: "J",
      voucherNo: "",
      accountCode: "",
      // 来自内部转账的数据
      summary: transferData.insideAbstract || "内部转账",
      remark: transferData.remark || "",
      // 其他字段
      attachmentCount: 1,
      transferId: transferData.id,
      transferData: transferData, // 保存完整的内部转账数据
    };

    // 打开凭证生成对话框
    voucherOpen.value = true;
  });
}

// 取消生成凭证
function cancelVoucher() {
  voucherOpen.value = false;
  proxy.resetForm("voucherFormRef");
}

// 提交生成凭证表单
function submitVoucherForm() {
  proxy.$refs["voucherFormRef"].validate((valid) => {
    if (valid) {
      // 显示加载中
      const loadingInstance = ElLoading.service({
        lock: true,
        text: "正在生成凭证，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      // 确保数据类型正确，并合并转账数据
      const submitData = {
        ...voucherForm.value,
        voucherNo: voucherForm.value.voucherNo.toString(),
        transferId: Number(voucherForm.value.transferId),
        attachmentCount: Number(voucherForm.value.attachmentCount || 1),
        // 添加内部转账相关数据
        insideAbstract: voucherForm.value.transferData?.insideAbstract,
        accountOut: voucherForm.value.transferData?.accountOut,
        accountJoin: voucherForm.value.transferData?.accountJoin,
        accountLimit: voucherForm.value.transferData?.accountLimit,
        userId: voucherForm.value.transferData?.userId,
      };

      // 删除不需要发送的字段
      delete submitData.transferData;

      // 详细打印提交数据
      console.log("提交凭证数据详情:", JSON.stringify(submitData));
      console.log("transferId类型:", typeof submitData.transferId);
      console.log("transferId值:", submitData.transferId);

      // 设置较长的超时时间
      generateVoucher(submitData)
        .then((response) => {
          loadingInstance.close();
          proxy.$modal.msgSuccess("凭证生成成功");
          voucherOpen.value = false;
          getList();

          // 跳转到凭证列表页面（可选）
          if (response.data && response.data.id) {
            // 方式1：直接跳转到凭证列表
            proxy.$router.push("/system/voucher");
          }
        })
        .catch((error) => {
          loadingInstance.close();
          console.error("凭证生成失败详情:", error);
          console.error("错误信息:", error.message);
          console.error("错误响应:", error.response?.data);
          proxy.$modal.msgError(
            "凭证生成失败：" + (error.message || "请联系管理员")
          );
        });
    }
  });
}

getList();
</script>

<style scoped>
.el-form-item__tip {
  font-size: 12px;
  color: #909399;
  line-height: 1;
  padding-top: 4px;
}
</style>
